# Copyright [2011] [Ilya Rudakov]
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from django.core.exceptions import ObjectDoesNotExist

from job_manager.models import Feed
from commands import getoutput
from job_manager.utils.logging_utils import getlogger

__author__ = 'irudakov'

LOG = getlogger(__name__)

def get_feed_state(feed_id):
    try:
        feed = Feed.objects.get(id=feed_id)
        pid = feed.pid
        is_running = __is_running__(pid)

        if not is_running and not feed.is_broken and pid is not None:
            return __create_feed_state__(feed_id, pid, "success")
        elif is_running:
            return __create_feed_state__(feed_id, pid, "is_running")
        elif not is_running and feed.is_broken:
            return __create_feed_state__(feed_id, pid, "is_broken")
        else:
            return __create_feed_state__(feed_id, pid, "stateless")
    except ObjectDoesNotExist:
        LOG.debug("When system tried to check job state it wasn't found. Job id: %s" % feed_id)
        return __create_feed_state__(feed_id, None, "stateless")

def __is_running__(pid):
    return getoutput("ps ux | awk '{print $2}' | grep %s | wc -l" % pid) == '1'

def __create_feed_state__(feed_id, pid, state_code):
    return {"feed_id": feed_id, "pid": pid, "state": state_code}